﻿using Application.Auth.Interfaces.Repositories;
using Application.Models;
using Application.Permissions.Interfaces;
using Application.Roles.Interfaces.Repositories;
using Domain.Roles.Interfaces;
using Infrastructure.Data.Contexts;
using Infrastructure.Repositories;
using Infrastructure.Services;
using Infrastructure.Services.Permissions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Shared.Configuration;

namespace Infrastructure
{
    public static class InfrastructureServiceCollectionExtensions
    {
        public static IServiceCollection AddInfrastructure(this IServiceCollection services,string configPath)
        {
            services.AddSingleton<IPermissionCache>(sp => new PermissionCache(configPath));
            services.AddSingleton<IPermissionRegistry, JsonPermissionRegistry>();
            services.AddSingleton<IPermissionService, PermissionService>();

            services.AddScoped<IRoleWriteRepository, RoleWriteRepository>();
            services.AddScoped<IRoleReadRepository, RoleReadRepository>();
            

            services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(RoleDto).Assembly));
            return services;
        }

        /// <summary>
        /// 注册数据库服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static IServiceCollection AddDatabaseContext(this IServiceCollection services, DatabaseSettings settings)
        {
            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(settings.ConnectionString,
                    sqlServerOptions => sqlServerOptions.EnableRetryOnFailure(
                        maxRetryCount: 5,
                        maxRetryDelay: TimeSpan.FromSeconds(settings.CommandTimeoutSeconds),
                        errorNumbersToAdd: null
                    )));

            return services;
        }
    }
}
